//
//  SearchBar.swift
//  TRHouse
//
//  Created by zhu xietong on 2018/5/16.
//  Copyright © 2018年 tianrun. All rights reserved.
//


import Foundation
import Eelay

public enum SearchBarStatus {
    case none
    case searchDone(String)
    case editing(String)
    case begin
    case lostFocus
}


open class SearchBar:JoView,UITextFieldDelegate{
    public let textBack = UIView()
    public let textField = UITextField()
    public let canleBt = UIButton()
    
    let searchIcon = UIImageView()

    
    public var historyMananger:SearchHistory = SearchHistory.shared
    public weak var owner:UIViewController?{
        didSet{
            self.mo_controller = owner
            historyView.mo_controller = owner
            if let ctr = owner as? TypeInitController{
                canleBt.ui.ntitle(title: "取消".loc).font(size: 14).padding(insets: [6,6]).ncolor(color: ctr.top_style.navTintColor)
                searchIcon.image = UIImage(named:"shop_search")?.rt_tintedImage(with:ctr.top_style.navTintColor)

            }
            historyView.container = owner?.view
        }
    }
    //    let holderView = HomeSearchPlaceholder()
    
    public var historyView = SearchHistoryView()
    
 
    public var status:SearchBarStatus = .none
    {
        didSet{
            
            switch status {
            case .editing(let str):
                debugPrint("editing text:\(str)")
            case .searchDone(let str):
                historyMananger.add(history: str)
            //                holderView.alpha = 0
            case .begin:
                textField.becomeFirstResponder()
                self.showCanleBt()
            
            case .lostFocus:
                textField.resignFirstResponder()
                historyView.hidden()
                self.hidenCanleBt()

            //                holderView.alpha = 1
            default:
                break
            }
            self.observerAction(status)
        }
    }
    
    open func showCanleBt() {
      
        weak var wself = self
        UIView.animate(withDuration: 0.16, animations: {
            guard let ws = wself else {return}
            wself?.rightC.constant = -(ws.canleBt.frame.size.width + 5)
            wself?.setNeedsLayout()
            wself?.layoutIfNeeded()
            wself?.canleBt.alpha = 1
        }) { (finish) in
            
        }
       
    }
    open func hidenCanleBt() {
        weak var wself = self

        UIView.animate(withDuration: 0.16, animations: {
            wself?.rightC.constant = 0
            wself?.canleBt.alpha = 0
            wself?.setNeedsLayout()
            wself?.layoutIfNeeded()
        }) { (finish) in
            
        }
        
    }
    
    public var observerAction:(SearchBarStatus) ->Void = {_ in}
    
    public var rightC = NSLayoutConstraint()
    
    
    
    override open func addLayoutRules() {
//        self.frame = [0,0,(Swidth-30),44]
        let menuIcon = UIImageView()
        let w = (Swidth-30)

        eelay = [
            [canleBt,[ee.Y.R,[0,5]]],
            [textBack,[ee.L.Y,[0.+1000,0]],"32",.<w.+750],
        ]
        canleBt.setContentConstrainToHighLever()
        canleBt.alpha = 0
        
        rightC = NSLayoutConstraint(item: textBack, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0)
        addConstraint(rightC)
//        print("++++___\(mo_theme.mode)")
        
        
        canleBt.ui.ntitle(title: "取消".loc).font(size: 14).padding(insets: [5,5]).ncolor(color: mo_theme.foreground)
        _ = textBack.bsui.background(color: mo_theme.dycolor(light: "#9992", dark: "#fff3")).corner5
        
        
        textBack.eelay = [
            [textField,[ee.L.R.Y,[10,-40,0]],"30"],
//            [menuIcon,[ee.Y.L,[0,8]],"13",17],
            [searchIcon,[ee.Y.R,[0,-8]],"24",24],
        ]
        
        searchIcon.alpha = 0.5
        menuIcon.image = UIImage(named: "sf_lb")
        textField.font = UIFont.systemFont(ofSize: 13)
        textField.textColor = mo_theme.foreground
        textField.placeholder = "请输入搜索关键字".loc
        textField.placeholderLabel?.font = UIFont.systemFont(ofSize: 13);
//        textField.setValue(UIFont.systemFont(ofSize: 12), forKeyPath: "_placeholderLabel.font")
        textField.returnKeyType = .search
        textField.delegate = self
        self.backgroundColor = .clear
        NotificationCenter.default.addObserver(self, selector: #selector(inputchange), name: UITextField.textDidChangeNotification, object: textField)
        
        weak var wself = self
        historyView.searchAction = { str in
            wself?.textField.text = str
            wself?.status = .searchDone(str)
            wself?.status = .lostFocus
        }
        
        //        holderView.backTouch = {
        //            wself?.textField.resignFirstResponder()
        //        }
        canleBt.addTarget(self, action: #selector(canle), for: .touchUpInside)
    }
    
    @objc open func canle(){
        self.status = .lostFocus
    }
    
    @objc open func inputchange() {
        if let txt = textField.text
        {
            //            var str = txt + string
            var str = txt
            let whitespace = CharacterSet.whitespacesAndNewlines
            
            var tempArray = str.components(separatedBy: whitespace)
            tempArray = tempArray.filter{
                $0 != ""
            }
            str = tempArray.joined(separator: "")
            self.status = .editing(str)
        }
    }
    
    open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if let txt = textField.text
        {
            var str = txt + string
            let whitespace = CharacterSet.whitespacesAndNewlines
            var tempArray = str.components(separatedBy: whitespace)
            tempArray = tempArray.filter{
                $0 != ""
            }
            str = tempArray.joined(separator: "")
        }
        return true
    }
    
    open func textFieldDidBeginEditing(_ textField: UITextField) {
        //        if let str = textField.text
        //        {
        //            if str.len > 1
        //            {
        //                searchStr = str
        //            }
        //        }
        historyView.historyMananger = self.historyMananger
        historyView.show()
        self.status = .begin
        
    }
    
    open func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if let str = textField.text
        {
            //            if str.len > 0
            //            {
            self.status = .searchDone(str)
            self.status = .lostFocus
//            historyView.hidden()
            textField.resignFirstResponder()
            return true
            //            }
        }
        
        self.status = .begin
        textField.resignFirstResponder()
        return false
    }
    
    override open var intrinsicContentSize: CGSize{
        get{
            return self.frame.size
        }
    }
    
    deinit{
        NotificationCenter.default.removeObserver(self, name: UITextField.textDidChangeNotification, object: textField)
    }
}




